package com.kevinwu.distributedsss.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户是否登录拦截器
 */
public class SecurityInterceptor implements HandlerInterceptor {

    /**
     * 进行登录校验
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取访问地址
        String requestURI = request.getRequestURI();
        //login地址直接方形 业务地址拦截
        if(requestURI.indexOf("/login")==-1){
            HttpSession session = request.getSession(false);
            if(session==null){
                response.sendRedirect(request.getContextPath() +"/login/loginindex");
                return false;
            } else if(!"admin".equals(session.getAttribute("username"))){
                response.sendRedirect(request.getContextPath() +"/login/loginindex");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
